const { ccclass, property } = cc._decorator;

import pageQuadtreeControl from "../cont/pageQuadtreeControl";

const qt = pageQuadtreeControl;

@ccclass
export default class quadTreeRect extends cc.Component {
    private speedx = 50;
    private speedy = 50;

    private xMin = 0;
    private yMin = 0;

    onLoad() {
        this.speedx *= Math.random() > 0.5 ? 1 : -1;
        this.speedy *= Math.random() > 0.5 ? 1 : -1;
    }

    start() {
        const box = this.node.getBoundingBoxToWorld();
        qt.insertRect(box.xMin, box.yMin, box.width, box.height, this.node.uuid);

        this.xMin = box.xMin;
        this.yMin = box.yMin;
    }

    move(dt: number) {
        const w = cc.winSize.width / 2;
        const h = cc.winSize.height / 2;

        const sx = this.speedx * dt;
        const sy = this.speedy * dt;

        // 更新坐标
        this.node.x += sx;
        this.node.y += sy;

        if (this.node.x <= -w || this.node.x >= w) {
            this.speedx *= -1;
        }

        if (this.node.y <= -h || this.node.y >= h) {
            this.speedy *= -1;
        }

        // 更新树
        this.xMin += sx;
        this.yMin += sy;
        qt.refreshRect(this.node.uuid, this.xMin, this.yMin);
    }

    update(dt: number) {
        this.move(dt);
        if (qt.retrieveRects(this.node.uuid).length) {
            this.node.color = cc.Color.RED;
        } else {
            this.node.color = cc.Color.GREEN;
        }
    }
}
